﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1.Utils
{
    internal class Style
    {
        /// <summary>
        /// 统一设置表格的样式
        /// </summary>
        /// <param name="dgv">要设置的表格样式</param>
        public static void DataGridViewStyle(DataGridView dgv)
        {
            // 防止卡顿
            //利用反射设置DataGridView的双缓冲
            Type dgvType = dgv.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(dgv, true, null);

            #region 设置表格样式
            // 设置列标题样式
            dgv.EnableHeadersVisualStyles = false;
            // 使用 Color.FromArgb(red, blue, green);          创建自定义颜色
            dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(154, 205, 50);
            dgv.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dgv.ColumnHeadersDefaultCellStyle.Font = new Font("楷体", 12F, FontStyle.Bold, GraphicsUnit.Point, 134);

            // 设置行标题样式
            dgv.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            // 偶数行的样式
            dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(77, 171, 247);
            #endregion

            #region 给行标题中添加行号
            // 添加事件，用于给行标题添加行号
            dgv.RowsAdded += dataGridView1_RowsAdded;
            // 解决行号两位数时数字显示不完整问题
            dgv.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            #endregion

            // 阻止表格自动生成列
            dgv.AutoGenerateColumns = false;
        }
        private static void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridView dataGridView = sender as DataGridView;
            for (int i = 0; i < e.RowCount; i++)
            {
                dataGridView.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                dataGridView.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
            }

            for (int i = e.RowIndex + e.RowCount; i < dataGridView.Rows.Count; i++)
            {
                dataGridView.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                dataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }
    }
}
